#include "BaseTimer.h"

namespace cm_base
{
    TimerNotification::TimerNotification() : m_interval(0), m_listener(NULL)
    {

    }
    TimerNotification::~TimerNotification()
    {

    }

    void TimerNotification::setInterval( long interval)
    {
        m_interval = interval;
    }

    long TimerNotification::getInterval()
    {
        return m_interval;
    }

    void TimerNotification::setContext(UInt32 context)
    {
        m_context = context;
    }

    UInt32 TimerNotification::getContext()
    {
        return m_context;
    }

    void TimerNotification::registerListener( BaseTimerListener* p_listener )
    {
        m_listener = p_listener;
    }

    BaseTimer::BaseTimer():m_stopFlag(false)
    {

    }

    BaseTimer::~BaseTimer()
    {
        //TODO:empty m_queue here
    }

    int BaseTimer::setup()
    {
        m_thread.start( *this );
        poco_debug(g_log_base, "Base Timer setup success");
        return 0;
    }

    void BaseTimer::start( long interval, UInt32 context, BaseTimerListener* p_cbListener  )
    {
        TimerNotification* p_tn = new TimerNotification;
        p_tn->setInterval( interval );
        p_tn->registerListener( p_cbListener );
        p_tn->setContext( context );
        start( p_tn );
    }

    int BaseTimer::teardown()
    {
        m_stopFlag = true;

        return 0;
    }

    void BaseTimer::start( TimerNotification* p_tn )
    {
        Poco::Timestamp ts;
        ts += (p_tn->m_interval) * 1000;
        m_queue.enqueueNotification(p_tn,ts);
    }

    void BaseTimer::run()
    {
        TimerNotification* p_tn = NULL;
        BaseTimerListener* p_tl = NULL;

        while( !m_stopFlag ){

            p_tn = (TimerNotification* )m_queue.waitDequeueNotification();
            p_tl = p_tn->m_listener;

            if( p_tl ){
                p_tl->onTimer( p_tn );
            }else{
                p_tn->release();
            }

            p_tn = NULL;
            p_tl = NULL;
        }
    }

}